<template>
  <div class="td-patient-me-base-info">
    <mt-cell title="我的头像">
      <span class="icon-path">
        <img v-if="loadData" :src="params.IconPath" width="100" height="100">
        <img
          v-if="loadData && !params.IconPath"
          src="../../../../assets/images/gril.png"
          width="100"
          height="100"
        >
        <input type="file" name="IconPathFile" @change="fileChange($event)">
      </span>
    </mt-cell>
    <mt-field label="姓名" placeholder="请输入姓名" v-model="params.UserName"></mt-field>
    <mt-field
      label="身份证号"
      placeholder="请输入身份证号"
      type="number"
      v-model="params.IDCard"
      @blur.native.capture="blurIDCard"
    ></mt-field>
    <mt-field
      label="生日"
      placeholder="请输入生日"
      v-if="loadData"
      v-model="params.Birthday"
      @focus.native.capture="$refs['Birthday'].open()"
    ></mt-field>
    <mt-field label="手机号" placeholder="请输入手机号" type="tel" v-model="params.MobilePhone"></mt-field>
    <mt-field label="邮箱" placeholder="请输入邮箱" type="email" v-model="params.Email"></mt-field>
    <div class="btnSubmit">
      <el-button
        type="primary"
        class="td-btn-patient-primary"
        style="width:80%;"
        round
        @click.native="btnSave();"
      >保存</el-button>
    </div>
    <mt-datetime-picker
      ref="Birthday"
      type="date"
      year-format="{value} 年"
      month-format="{value} 月"
      date-format="{value} 日"
      :startDate="new Date('1600-01-01')"
      v-if="loadData"
      v-model="date"
      @confirm="handleChange"
    ></mt-datetime-picker>
  </div>
</template>

<script>
import UserService from "../../../../_services/user.service";
export default {
  name: "TianDingPatientMeBaseInfoComponent",
  data() {
    return {
      params: {
        UserID: 0,
        UserName: "",
        MobilePhone: "",
        Password: "",
        IDCard: "",
        Birthday: "",
        Email: "",
        MateName: "",
        MateBirthDay: "",
        MateIDCard: "",
        IconPath: "",
        RegisterTime: "",
        LoginTime: "",
        UserStatus: 0,
        OpenID: ""
      },
      tempIconPath: "",
      date: new Date(),
      loadData: false
    };
  },
  mounted() {
    this.params = this.utils$.dataFormat(
      JSON.parse(this.local$.getItem("tdUser"))
    );

    if (!this.utils$.isEmpty(this.params.Birthday)) {
      this.params.Birthday = this.utils$.getDate("-");
    } else {
      this.params.Birthday = this.params.Birthday.split("T")[0];
      this.date = new Date(this.params.Birthday);
    }

    this.loadData = true;
  },
  methods: {
    blurIDCard() {
      if (!this.utils$.isEmpty(this.params.IDCard)) {
        return;
      }
      let year = this.params.IDCard.substring(6, 10);
      let month = this.params.IDCard.substring(10, 12);
      let day = this.params.IDCard.substring(12, 14);
      this.params.Birthday = `${year}-${month}-${day}`;
    },
    handleChange(value) {
      let newDate = new Date(value).toLocaleDateString().replace(/\//g, "-");
      let year = newDate.split("-")[0];
      let month = parseInt(newDate.split("-")[1]);
      let day = parseInt(newDate.split("-")[2]);
      if (month < 10) {
        month = `0${month}`;
      }
      if (day < 10) {
        day = `0${day}`;
      }
      this.params.Birthday = `${year}-${month}-${day}`;
    },
    fileChange(event) {
      let files = event.target.files[0];
      let fileName = files.name;
      let file = /\.[^\.]+/.exec(fileName);
      let imageType = file[0].replace(".", "").toString();
      let arr = ["jpg", "png", "jpeg", "bmp"];
      if (!arr.includes(imageType)) {
        this.toast$(`图片格式不正确(${arr.toString()})`);
        return;
      }

      let reader = new FileReader();
      reader.readAsDataURL(files);
      reader.onload = e => {
        let base64 = e.target.result;
        this.params.IconPath = base64;
      };
    },
    btnSave() {
      let iconPath = "";
      if (this.utils$.isEmpty(this.params.IconPath)) {
        if (this.params.IconPath.indexOf("http") === -1) {
          iconPath = this.utils$.removeBase64Prefix(this.params.IconPath);
        }
      }

      if (!this.utils$.isEmpty(this.params.UserName)) {
        this.toast$("请输入姓名");
        return;
      }

      if (!this.utils$.isEmpty(this.params.IDCard)) {
        this.toast$("请输入身份证号");
        return;
      }

      if (!this.utils$.isEmpty(this.params.IDCard)) {
        this.toast$("请输入身份证号");
        return;
      }

      if (!this.utils$.isEmpty(this.params.Birthday)) {
        this.toast$("请输入生日");
        return;
      }

      if (!this.utils$.isEmpty(this.params.MobilePhone)) {
        this.toast$("请输入手机号");
        return;
      }

      if (!this.utils$.isEmpty(this.params.Email)) {
        this.toast$("请输入邮箱");
        return;
      }

      this.indicator$.open("请稍后...");

      let params = {
        UserID: this.params.UserID,
        MobilePhone: this.params.MobilePhone,
        Password: null,
        UserName: this.params.UserName,
        IDCard: this.params.IDCard,
        Birthday: this.params.Birthday,
        Email: this.params.Email,
        MateName: this.params.MateName,
        MateBirthDay: this.params.MateBirthDay,
        MateIDCard: this.params.MateIDCard,
        UserStatus: this.params.UserStatus,
        IconPath: iconPath
      };

      UserService.updateUserInfo(params).then(response => {
        setTimeout(() => {
          if (response && response.Data > 0) {
            this.toast$("保存成功");
          } else {
            this.toast$("保存失败");
          }
          this.indicator$.close();
        }, 1000);
        UserService.getUserInfoByID({ userID: params.UserID }).then(args => {
          if (args && args.Data) {
            args.Data.Age = this.utils$.getAge(args.Data.Birthday);
            this.local$.removeItem("tdUser");
            this.local$.setItem("tdUser", JSON.stringify(args.Data));
          }
        });
      });
    }
  }
};
</script>

